package cas;

import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.globes.Globe;

import java.util.List;

import bean.RuteBean;

public class GPSSimulator implements Runnable{
	private Identity myIdentity;
	private Speed speed;
	private boolean running;
	private boolean available;
	private double curSpeed;
	private static Globe globe;
	public GPSSimulator(Identity iden, double curSpeed, double destSpeed, Globe globe){
		super();
		GPSSimulator.globe = globe;
		myIdentity = iden;
		myIdentity.setUrutan(0);
		List<RuteBean> rute = myIdentity.getRute();
		myIdentity.setCurCoord(LatLon.fromDegrees(rute.get(0).getKoordinat().getLatitude(), rute.get(0).getKoordinat().getLongitude()));
		available = true;
		this.speed = new Speed(curSpeed, destSpeed);
		System.out.println(myIdentity);
	}


	@Override
	public void run() {
		running = true;
		while(myIdentity.getUrutan()<myIdentity.getRute().size()-1&running){
			LatLon koor1 = myIdentity.getRute().get(myIdentity.getUrutan()).getCoordinate();
			LatLon koor2 = myIdentity.getRute().get(myIdentity.getUrutan()+1).getCoordinate();
			Angle angle = LatLon.greatCircleAzimuth(koor1, koor2);
			speed.calculateSpeed();
			curSpeed = Math.toDegrees(speed.getCurrentSpeed()/globe.getRadiusAt(myIdentity.getCurCoord()));
			double vLat = curSpeed*Math.sin(Math.toRadians(90)-angle.getRadians());
			double vLon = curSpeed*Math.cos(Math.toRadians(90)-angle.getRadians());
			myIdentity.setCurCoord(LatLon.fromDegrees(
					myIdentity.getCurCoord().getLatitude().getDegrees()+vLat, 
					myIdentity.getCurCoord().getLongitude().getDegrees()+vLon));
			if(LatLon.greatCircleDistance(koor1, myIdentity.getCurCoord()).getDegrees()>=LatLon.greatCircleDistance(koor1, koor2).getDegrees()){
				myIdentity.setCurCoord(LatLon.fromDegrees(koor2.getLatitude().getDegrees(), koor2.getLongitude().getDegrees()));
				myIdentity.setUrutan(myIdentity.getUrutan()+1);
			}
			available = true;
		}	
		running = false;
	}
	public double getCurSpeed(){
		return curSpeed;
	}
	public Identity getMyIdentity() {
		return myIdentity;
	}
	public void setMyIdentity(Identity myIdentity) {
		this.myIdentity = myIdentity;
	}
	public Speed getSpeed() {
		return speed;
	}
	public void stop(){
		running = false;
	}
	public boolean isRunning(){
		return running;
	}
	public static Globe getGlobe(){
		return globe;
	}
	public LatLon getCurCoordinate(){
		while(!available){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		available = false;
		return LatLon.fromDegrees(myIdentity.getCurCoord().getLatitude().getDegrees(), myIdentity.getCurCoord().getLongitude().getDegrees());	

	}
}
